import java.io.*;
import nodes.*;
import visitors.*;
import table.*;
import java_cup.runtime.*;

public class TestScanner
{
    public TestScanner(File path) throws Exception
    {
        recurse(path);
    }

    private void recurse(File file) throws Exception
    {
        if (!file.isHidden())
        {
            if (file.isDirectory())
            {
                File[] files = file.listFiles();
                for (int i = 0; i < files.length; i++)
                {
                    recurse(files[i]);
                }
            }
            else
            {
                runScanner(file);
            }
        }
    }
    
    private void runScanner(File file) throws Exception
    {
        ErrorHandler.reset();
        System.out.println();
        System.out.println("Running tests in: " + file.getAbsolutePath());

        Yylex myScanner = new Yylex(new FileReader(file));
        parser myParser = new parser(myScanner);
        try {
            Symbol result = myParser.parse();
            ProgramNode root = (ProgramNode) result.value;

            // Uncomment the following two lines to enable the PrettyPrintVisitor
            //PrettyPrintVisitor printVisitor = new PrettyPrintVisitor();
            //root.accept(printVisitor);

            SymbolTableVisitor symbolVisitor = new SymbolTableVisitor();
            SymbolTable table = (SymbolTable) root.accept(symbolVisitor);

            // Uncomment the following two lines to enable the SymbolPrettyPrintVisitor
            //SymbolTablePrettyPrintVisitor stppv = new SymbolTablePrettyPrintVisitor();
            //stppv.visit(table);

            TypeAndScopeVisitor tsVisitor = new TypeAndScopeVisitor(table);
            root.accept(tsVisitor);

            System.out.println("Finished all tests in: " + file.getName());
            ErrorHandler.summary();
        } catch (Exception e) {
            System.out.println("=====Parsing FAILED=====");
            e.printStackTrace();
        }
    }
    
    public static void main(String[] args)
    {
        try
        {
            File file = new File(args[0]);
            TestScanner testScanner = new TestScanner(file);
        }
        catch (ArrayIndexOutOfBoundsException aioob)
        {
            System.out.println("usage: java TestScanner <path>");
            System.out.println("Where <path> is the pathname of a test file or folder of test files.");
        }
        catch (Exception e)
        {
            System.out.println("There has been an error:");
            e.printStackTrace();
        }
    }
}